package org.ncibi.cytoscape.metscape.task;

import org.ncibi.cytoscape.metscape.network.MetScapeNetworks;

import cytoscape.CyNetwork;
import cytoscape.Cytoscape;
import cytoscape.layout.CyLayoutAlgorithm;
import cytoscape.layout.CyLayouts;
import cytoscape.task.Task;
import cytoscape.task.TaskMonitor;
import cytoscape.task.ui.JTaskConfig;
import cytoscape.task.util.TaskManager;

public class RestoreNetworkTask implements Task {

	private CyNetwork network;

	private TaskMonitor taskMonitor;
	private boolean interrupted = false;

	public static void restoreCyNetwork(CyNetwork network) {
		RestoreNetworkTask task = new RestoreNetworkTask(network);
		configureAndRunTask(task);
	}
	
	public RestoreNetworkTask(CyNetwork network) {
		this.network = network;
	}
	
	private static void configureAndRunTask(RestoreNetworkTask task) {
		// Configure JTask Dialog Pop-Up Box
		JTaskConfig jTaskConfig = new JTaskConfig();
		jTaskConfig.setOwner(Cytoscape.getDesktop());
		jTaskConfig.displayCancelButton(true);
		jTaskConfig.displayStatus(true);

		// Execute Task in New Thread; pops open JTask Dialog Box.
		TaskManager.executeTask(task, jTaskConfig);
	}

	public void setTaskMonitor(TaskMonitor monitor)
			throws IllegalThreadStateException {
		taskMonitor = monitor;
	}

	public void halt() {
		interrupted = true;
	}

	public String getTitle() {
		return "Restore Network";
	}

	public void run() {
		try {
			taskMonitor.setPercentCompleted(-1);
			taskMonitor.setStatus("Restoring original network...");
			MetScapeNetworks.restoreOriginalNetwork(network);
			CyLayoutAlgorithm layout = CyLayouts.getLayout("force-directed");
			layout.doLayout(Cytoscape.getCurrentNetworkView(), taskMonitor);
			taskMonitor.setStatus("Complete");
			taskMonitor.setPercentCompleted(100);

		} catch (Throwable t) {
			if (!interrupted)
				taskMonitor.setException(t, "Network restoration failed");
		}

	}
}
